import 'package:flutter/material.dart';
import 'package:hello_flutter/base/index.dart';

class InfiniteGridViewWidget extends BasePage {
  const InfiniteGridViewWidget({super.key});

  @override
  String getPageTitle() => 'InfiniteGridView';

  @override
  Widget buildBody(BuildContext context) {
    return const Column(
      children: [
        ListTile(
          title: Text('Icons'),
        ),
        Expanded(
          child: _InfiniteGridViewRoute(),
        ),
      ],
    );
  }
}

class _InfiniteGridViewRoute extends StatefulWidget {
  const _InfiniteGridViewRoute({super.key});

  @override
  State<_InfiniteGridViewRoute> createState() => _InfiniteGridViewRouteState();
}

class _InfiniteGridViewRouteState extends State<_InfiniteGridViewRoute> {
  final List<IconData> _icons = [Icons.downloading];

  @override
  void initState() {
    super.initState();
    _retrieveIcons();
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 1,
        ),
        itemCount: _icons.length,
        itemBuilder: (context, index) {
          if (index == _icons.length - 1) {
            if (_icons.length - 1 < 100) {
              _retrieveIcons();
              return Container(
                alignment: Alignment.center,
                child: const SizedBox.square(
                  dimension: 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    color: Colors.red,
                  ),
                ),
              );
            } else {
              return Container(
                padding: const EdgeInsets.all(16),
                alignment: Alignment.center,
                child: const Text(
                  '没有更多了',
                  style: TextStyle(color: Colors.grey),
                ),
              );
            }
          }
          return Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('${index + 1}'),
              Icon(_icons[index]),
            ],
          );
        });
  }

  void _retrieveIcons() async {
    await Future.delayed(const Duration(seconds: 2));
    setState(() {
      _icons.insertAll(_icons.length - 1, [
        Icons.ac_unit,
        Icons.airport_shuttle,
        Icons.all_inclusive,
        Icons.beach_access,
        Icons.cake,
        Icons.free_breakfast,
      ]);
    });
  }
}
